package client;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketTimeoutException;

import xmlparser.XmlParser;

import client.ClientMain;

public class TClient extends Thread{
	
	private InetAddress hostAddress ;
	private int serverPort ;
	private byte[] sentBuffer ;
	private DatagramSocket seSocket = null;
    private String receivedFileName = "clientreceived_gen.xml" ;
    final static int buffsize = 1024;
    private static byte[] receivedBuffer = new byte[buffsize];
    
	public TClient(InetAddress hostAddress , int serverPort, byte[] sentBuffer){
		this.hostAddress = hostAddress;
		this.serverPort = serverPort;
		this.sentBuffer =sentBuffer;
	}
	 /**
     * Run method
     */
	public void run(){
		boolean state = true ;
		while(state){
				
			//create socket
			seSocket = ClientMain.createSocket(); 
			 
		    //// SEND PACKET to the server & close the socket
		    DatagramPacket sendPacket = new DatagramPacket(sentBuffer, sentBuffer.length, hostAddress , serverPort);
		    System.out.println(" ###########################################" );
	   	    System.out.println("C : Client send from : " + seSocket.getLocalPort() +", to  : " + sendPacket.getPort() );
		
		    ClientMain.sendpacket(seSocket, sendPacket);
		
		    //// RECEIVE PACKET on the local port previously randomly selected port
		
		    DatagramPacket receivePacket = new DatagramPacket(receivedBuffer, receivedBuffer.length);
		
		    System.out.println("C : Client waitting feedbacks from : " + seSocket.getLocalPort());
		    receivePacket = ClientMain.receivepacket(seSocket);
		
		    String received = new String(receivePacket.getData(), 0, receivePacket.getLength());
		    System.out.println("C : Client receive data "+ received);
		    XmlParser.byteToWriteXmlFile(receivePacket.getData(), receivedFileName);
		
		    try {
		        //Write into file 
		        System.out.println("C : Write to file " + receivedFileName);
		
		        FileOutputStream out = new FileOutputStream(new File(receivedFileName));
		        out.write(receivePacket.getData());
		        out.close();
		    
		    } catch (SocketTimeoutException e){
		    	System.out.println("C : Server not respond in time... Exiting."+e);
		        seSocket.close();
		    	System.exit(-2);
		    	
		    }catch(IOException e) {
		    	System.out.println("C : Cannot write to file " + receivedFileName + ", reason : " + e);
		    }
		    state= false;
		}
	}
}
